package com.tadpole.music.view.activity.study;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.shuyu.waveview.AudioPlayer;
import com.tadpole.music.R;
import com.tadpole.music.bean.study.ErrorSingleQuestionBean;
import com.tadpole.music.config.Constant;
import com.tadpole.music.config.UrlConfig;
import com.tadpole.music.iView.study.ErrorSingleQuestionIView;
import com.tadpole.music.presenter.study.ErrorSingleQuestionPresenter;
import com.tadpole.music.utils.NoDoubleClickListener;
import com.tadpole.music.utils.SpUtil;
import com.tadpole.music.utils.largeImage.InputStreamBitmapDecoderFactory;
import com.tadpole.music.utils.largeImage.LargeImageView;
import com.tadpole.music.view.activity.base.BaseActivity;
import com.tadpole.music.view.activity.base.LookBigPicActivity;
import com.tadpole.music.view.activity.login.LoginActivity;
import com.tadpole.music.view.activity.question.RealAnswerActivity;
import com.tadpole.music.view.activity.question.SimulationQuestionActivity;
import com.tadpole.music.view.widget.BigImagePopup;
import com.tadpole.music.view.widget.LollipopFixedWebView;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;

/**
 * 错题页面
 * Created By 孙岩
 * on 2020/10/10
 */
public class ErrorQuestionActivity extends BaseActivity implements ErrorSingleQuestionIView {
    //回退
    private View view_back_icon;
    //标题
    private TextView actionbar_title;
    //imageView
    private LargeImageView ivImage;
    //title
    private LollipopFixedWebView tvTitle;
    private LinearLayout llA;
    private LinearLayout llB;
    private LinearLayout llC;
    private LinearLayout llD;
    private TextView tvA;
    private TextView tvB;
    private TextView tvC;
    private TextView tvD;
    private ImageView ivA;
    private ImageView ivB;
    private ImageView ivC;
    private ImageView ivD;
    private TextView tvAText;
    private TextView tvBText;
    private TextView tvCText;
    private TextView tvDText;
    //正确答案
    private TextView tvAnswer;
    private RelativeLayout rlAnswer;
    private ErrorSingleQuestionPresenter errorSingleQuestionPresenter;

    //题目id
    private int id;
    //选择的答案
    private String error;

    //播放text的
    private static AudioPlayer audioText;
    //播放背景的
    private static AudioPlayer audioBg;
    //有音频的选择题 播放12345
    private static MediaPlayer media;
    private String image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_error_question);
        initViews();
        initListeners();
        id = getIntent().getIntExtra("id",0);
        error = getIntent().getStringExtra("error");
        errorSingleQuestionPresenter = new ErrorSingleQuestionPresenter();
        errorSingleQuestionPresenter.attachView(this);
        errorSingleQuestionPresenter.getErrorQuestion(id);
    }

    //初始化控件
    private void initViews(){
        view_back_icon = findViewById(R.id.view_back_icon);
        actionbar_title = findViewById(R.id.actionbar_title);
        tvTitle = findViewById(R.id.tvTitle);
        ivImage = findViewById(R.id.ivImage);
        actionbar_title.setText("错题");
        llA = findViewById(R.id.llA);
        llB = findViewById(R.id.llB);
        llC = findViewById(R.id.llC);
        llD = findViewById(R.id.llD);
        tvA = findViewById(R.id.tvA);
        tvB = findViewById(R.id.tvB);
        tvC = findViewById(R.id.tvC);
        tvD = findViewById(R.id.tvD);
        ivA = findViewById(R.id.ivA);
        ivB = findViewById(R.id.ivB);
        ivC = findViewById(R.id.ivC);
        ivD = findViewById(R.id.ivD);
        tvAText = findViewById(R.id.tvAText);
        tvBText = findViewById(R.id.tvBText);
        tvCText = findViewById(R.id.tvCText);
        tvDText = findViewById(R.id.tvDText);
        tvAnswer = findViewById(R.id.tvAnswer);
        rlAnswer = findViewById(R.id.rlAnswer);
        tvTitle.setBackgroundColor(0);
    }

    //初始化监听器
    private void initListeners(){
        view_back_icon.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                ErrorQuestionActivity.this.finish();
            }
        });

        ivImage.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                ArrayList<String> a = new ArrayList<>();
                a.add(image);
                BigImagePopup bigImagePopup = new BigImagePopup(ErrorQuestionActivity.this,0,a);
                bigImagePopup.showPopupWindow();
            }
        });
    }

    @Override
    public void show401() {
        SpUtil.getInstance(this).putString(Constant.TOKEN,"");
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }

    @SuppressLint({"UseCompatLoadingForDrawables","CheckResult"})
    @Override
    public void showQuestion(ErrorSingleQuestionBean.DataBean bean) {
        RequestOptions requestOptions = new RequestOptions()
                .placeholder(R.mipmap.app_icon)
                .error(R.mipmap.app_icon)
                .priority(Priority.HIGH)
                .diskCacheStrategy(DiskCacheStrategy.ALL);
        if (bean.getTitle_img().equals("")) {
            ivImage.setVisibility(View.GONE);
        } else {
            ivImage.setVisibility(View.VISIBLE);
            image = Constant.IMAGE_HEAD +  bean.getTitle_img();
            Glide.with(this).load(Constant.IMAGE_HEAD +  bean.getTitle_img()).downloadOnly(new SimpleTarget<File>() {

                @Override
                public void onResourceReady(final File resource, Transition<? super File> transition) {

                    try {
                        //主线程
                        ivImage.setImage(new InputStreamBitmapDecoderFactory(new FileInputStream(resource)));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        String url = UrlConfig.getTitle + "q_type=question&id=" + bean.getId();
        tvTitle.loadUrl(url);

        if (bean.getAnswer_type() == 1 && bean.getRight_answer() != -1) {//文字

            ivA.setVisibility(View.GONE);
            ivB.setVisibility(View.GONE);
            ivC.setVisibility(View.GONE);
            ivD.setVisibility(View.GONE);
            tvAText.setVisibility(View.VISIBLE);
            tvBText.setVisibility(View.VISIBLE);
            tvCText.setVisibility(View.VISIBLE);
            tvDText.setVisibility(View.VISIBLE);

            tvAText.setText(bean.getAnswer_a());
            tvBText.setText(bean.getAnswer_b());
            tvCText.setText(bean.getAnswer_c());
            tvDText.setText(bean.getAnswer_d());

            if (bean.getAnswer_c().equals("")) {
                llC.setVisibility(View.GONE);
            }
            if (bean.getAnswer_d().equals("")) {
                llD.setVisibility(View.GONE);
            }

        } else if (bean.getAnswer_type() == 2 || bean.getAnswer_type() == 5) {//图片

            ivA.setVisibility(View.VISIBLE);
            ivB.setVisibility(View.VISIBLE);
            ivC.setVisibility(View.VISIBLE);
            ivD.setVisibility(View.VISIBLE);
            tvAText.setVisibility(View.GONE);
            tvBText.setVisibility(View.GONE);
            tvCText.setVisibility(View.GONE);
            tvDText.setVisibility(View.GONE);

            Glide.with(this).load(Constant.IMAGE_HEAD + bean.getAnswer_a()).apply(requestOptions).into(ivA);
            Glide.with(this).load(Constant.IMAGE_HEAD + bean.getAnswer_b()).apply(requestOptions).into(ivB);
            Glide.with(this).load(Constant.IMAGE_HEAD + bean.getAnswer_c()).apply(requestOptions).into(ivC);
            Glide.with(this).load(Constant.IMAGE_HEAD + bean.getAnswer_d()).apply(requestOptions).into(ivD);
            if (bean.getAnswer_c().equals("")) {
                llC.setVisibility(View.GONE);
            }
            if (bean.getAnswer_d().equals("")) {
                llD.setVisibility(View.GONE);
            }
        }else{
            llA.setVisibility(View.GONE);
            llB.setVisibility(View.GONE);
            llC.setVisibility(View.GONE);
            llD.setVisibility(View.GONE);
            rlAnswer.setVisibility(View.GONE);
        }

        switch (error) {
            case "1":
                tvA.setBackground(getResources().getDrawable(R.drawable.shape_main_circular_solid));
                tvB.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                tvC.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                tvD.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                break;
            case "2":
                tvA.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                tvB.setBackground(getResources().getDrawable(R.drawable.shape_main_circular_solid));
                tvC.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                tvD.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                break;
            case "3":
                tvA.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                tvB.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                tvC.setBackground(getResources().getDrawable(R.drawable.shape_main_circular_solid));
                tvD.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                break;
            case "4":
                tvA.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                tvB.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                tvC.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                tvD.setBackground(getResources().getDrawable(R.drawable.shape_main_circular_solid));
                break;
        }

        if (bean.getRight_answer() == 1) {
            tvAnswer.setText("正确答案是: A");
        }else if (bean.getRight_answer() == 2) {
            tvAnswer.setText("正确答案是: B");
        }else if (bean.getRight_answer() == 3) {
            tvAnswer.setText("正确答案是: C");
        }else if (bean.getRight_answer() == 4) {
            tvAnswer.setText("正确答案是: D");
        }

        playText( bean.getTitle_sound(), bean.getBg_sound(),bean.getPlay_times());

    }

    //播放题干
    @SuppressLint("HandlerLeak")
    private void playText(final String title_sound, final String bg_sound,final int cycler){
        if(title_sound.equals("")){
            playBgSound(bg_sound,0,cycler);
        }else{
            audioText = new AudioPlayer(ErrorQuestionActivity.this, new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case AudioPlayer.HANDLER_CUR_TIME://更新的时间
                            break;
                        case AudioPlayer.HANDLER_COMPLETE://text播放结束
                            playCount(bg_sound,0,cycler);
                            break;
                        case AudioPlayer.HANDLER_PREPARED://播放开始
                            break;
                        case AudioPlayer.HANDLER_ERROR://播放错误

                            break;
                    }

                }
            });
            audioText.playUrl(Constant.IMAGE_HEAD + title_sound);
        }
    }

    //播放第几遍
    @SuppressLint("HandlerLeak")
    private void playCount(final String bg_sound,final int count,final int cycler){
        if(bg_sound.equals("")){

        }else{
            if (media != null) {
                media.stop();
                media.release();
            }
            media = MediaPlayer.create(ErrorQuestionActivity.this, rediaCount(count));
            media.start();

            media.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    playBgSound(bg_sound, count + 1,cycler);
                }
            });

        }
    }

    //播放背景
    @SuppressLint("HandlerLeak")
    private void playBgSound(final String bg_sound,final int count,final int cycler){

        audioBg = new AudioPlayer(ErrorQuestionActivity.this, new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case AudioPlayer.HANDLER_CUR_TIME://更新的时间
                        break;
                    case AudioPlayer.HANDLER_COMPLETE://播放结束
                        if (cycler == 1) {

                        } else if (cycler == 2) {
                            if (count != cycler) {
                                playCount(bg_sound, 1, cycler);
                            }

                        } else if (cycler == 3) {
                            if (cycler - count == 2) {//波了一遍了
                                playCount(bg_sound, 1, cycler);

                            } else if (cycler - count == 1) {
                                playCount(bg_sound, 1, cycler);
                            }

                        } else if (cycler == 4) {


                        } else if (cycler == 5) {

                        }
                        break;
                    case AudioPlayer.HANDLER_PREPARED://播放开始
                        break;
                    case AudioPlayer.HANDLER_ERROR://播放错误
                        break;
                }

            }
        });
        audioBg.playUrl(Constant.IMAGE_HEAD + bg_sound);
    }

    //第一遍 第二遍
    private int rediaCount(int index) {
        int redia = 0;
        switch (index) {
            case 0:
                redia = R.raw.to1;
                break;
            case 1:
                redia = R.raw.to2;
                break;
        }
        return redia;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //停止播放
        if ( audioBg!= null) {
            audioBg.stop();
            audioBg = null;
        }
        if (audioText != null) {
            audioText.stop();
            audioText = null;
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        //停止播放
        if ( audioBg!= null) {
            audioBg.stop();
            audioBg = null;
        }
        if (audioText != null) {
            audioText.stop();
            audioText = null;
        }
    }
}
